package org.eclipse.soc.ide4edu.assignment.operations;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;

public class AssignmentZipOperation {

	final int BUFFER = 2048;
	String savePath;
	private String assignmentPath = null;
	String assignmentName = null;

	private void addDirectoryToZip(String inPath, String savePath,
			ZipOutputStream zipStream) throws IOException

	{
		BufferedInputStream inStream = null;

		if (new File(inPath).list().length == 0) {
			zipStream.putNextEntry(new ZipEntry(getRelativePath(inPath)
					+ getSeparator() + ".tmp"));
			zipStream.closeEntry();
			return;
		}

		File files[] = new File(inPath).listFiles();
		byte[] data = new byte[BUFFER];

		for (int i = 0; i < files.length; i++) {
			String fullPath = files[i].getPath();

			if (fullPath.compareToIgnoreCase(savePath) == 0)
				continue;

			if (new File(fullPath).isDirectory()) {

				addDirectoryToZip(fullPath, savePath, zipStream);
			}

			else {
				inStream = new BufferedInputStream(
						new FileInputStream(fullPath), BUFFER);

				zipStream.putNextEntry(new ZipEntry(getRelativePath(fullPath)));
				int len;
				while ((len = inStream.read(data, 0, BUFFER)) != -1)
					zipStream.write(data, 0, len);

				zipStream.closeEntry();

			}
		}

		inStream.close();

	}

	private final String getRelativePath(String absPath) {

		String relativePath = absPath.substring(assignmentPath.length());
		return (new String(getSeparator() + assignmentName + relativePath));
	}

	public String getSavePath() {
		return savePath;
	}

	private String getSeparator() {
		return System.getProperty("file.separator");
	}

	private boolean getUserChoice(Shell shell) {
		MessageBox msg = new MessageBox(shell, SWT.CANCEL | SWT.OK
				| SWT.ICON_WARNING);
		msg.setText("File exists!");
		msg.setMessage("Click OK to Overwrite");
		if (msg.open() == SWT.CANCEL)
			return false;
		return true;
	}

	public void saveAsZIP(String assignmentName, String fullPath, Shell shell,
			IProgressMonitor monitor) throws IOException, CoreException {

		this.assignmentName = assignmentName;
		assignmentPath = new String(fullPath);
		final String filename = assignmentName;
		savePath = assignmentPath + getSeparator() + filename + ".zip";

		if (new File(savePath).exists() == true) {
			if (getUserChoice(shell) == false)
				return;
		}

		ZipOutputStream zipStream = new ZipOutputStream(
				new BufferedOutputStream(new FileOutputStream(savePath)));

		addDirectoryToZip(fullPath, savePath, zipStream);
		zipStream.flush();
		zipStream.close();
		monitor.worked(5);
	}

}
